package org.jeecg.modules.demo.pusettlement.service.impl;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.dto.message.TemplateMessageDTO;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.demo.pubuyorder.entity.PuBuyOrder;
import org.jeecg.modules.demo.pubuyorder.mapper.PuBuyOrderMapper;
import org.jeecg.modules.demo.pusettlement.entity.PuSettlement;
import org.jeecg.modules.demo.pusettlement.entity.PuSettlementVo;
import org.jeecg.modules.demo.pusettlement.mapper.PuSettlementMapper;
import org.jeecg.modules.demo.pusettlement.service.IPuSettlementService;
import org.jeecg.modules.demo.utils.BigDecimalUtil;
import org.jeecg.modules.demo.utils.generateOddUtil;
import org.jeecg.modules.demo.warehouseorder.entity.WarehouseOrder;
import org.jeecg.modules.demo.warehouseorder.mapper.WarehouseOrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 采购结算
 * @Author: jeecg-boot
 * @Date:   2021-12-06
 * @Version: V1.0
 */
@Service
public class PuSettlementServiceImpl extends ServiceImpl<PuSettlementMapper, PuSettlement> implements IPuSettlementService {
    @Resource
    private PuSettlementMapper puSettlementMapper;
    @Resource
    private WarehouseOrderMapper warehouseOrderMapper;
    @Resource
    private PuBuyOrderMapper puBuyOrderMapper;
    @Autowired
    private ISysBaseAPI sysBaseAPI;

    private static final String TITLE = "单据审核";


    private String getMessage(String name,String date) {
        String str ="由【"+name+"】于【"+date+"】发起的采购结算单需要您的审核，请及时查看！";
        return str;
    }

    @Override
    public String getMaxCode(){
        return puSettlementMapper.getMaxCode();
    }

    @Override
    public List<PuSettlement> getWriteOffDetails(PuSettlement puSettlement){
        return puSettlementMapper.getWriteOffDetails(puSettlement);
    }

    @Override
    public Double getTotailByNumber(PuSettlement puSettlement){
        return puSettlementMapper.getTotailByNumber(puSettlement);
    }

    @Override
    public PuSettlement getByPusNo(String str){
        return puSettlementMapper.getByPusNo(str);
    }
    @Override
    public List<String> selectByRkOrder(String number){
        return puSettlementMapper.selectByRkOrder(number);
    }

    @Override
    public Page<PuSettlementVo> getList(Page<PuSettlementVo> page, PuSettlement puSettlement){
        return page.setRecords(puSettlementMapper.getList(page,puSettlement));
    }

    public List<PuSettlement> getListByPoOrder(String str){
        return puSettlementMapper.getByPoOrder(str);
    }
    public List<PuSettlement> getYjByOrder(String str,Page<PuSettlement> page){
        return puSettlementMapper.getYjByOrder(str,page);
    }

    @Override
    public Map<String,Double> getYkTotailByOrder(String str){
        return puSettlementMapper.getYkTotailByOrder(str);
    }

    @Override
    @Transactional
    public boolean waiveChecKSettlement(PuSettlement puSettlement){
        try{
            puSettlement.setShenhe(0);
            puSettlement.setShTime(null);
            puSettlementMapper.updateById(puSettlement);
            if(puSettlement.getDjlx()==2){

                WarehouseOrder warehouseOrder = warehouseOrderMapper.getByWoNo(puSettlement.getWoNo());
                warehouseOrder.setFpsl(new BigDecimal(BigDecimalUtil.sub(warehouseOrder.getFpsl().doubleValue(),puSettlement.getQoQuantity().doubleValue())));
                warehouseOrder.setFpje(new BigDecimal(BigDecimalUtil.sub(warehouseOrder.getFpje().doubleValue(),puSettlement.getWsje().doubleValue())));
                warehouseOrder.setZgsl(new BigDecimal(BigDecimalUtil.add(warehouseOrder.getZgsl().doubleValue(),puSettlement.getQoQuantity().doubleValue())));
                Double cb = BigDecimalUtil.mul(warehouseOrder.getWsdj().doubleValue(),warehouseOrder.getZgsl().doubleValue());
                warehouseOrder.setZxcb(new BigDecimal(BigDecimalUtil.add(cb,warehouseOrder.getFpje().doubleValue())));
                warehouseOrderMapper.updateById(warehouseOrder);
            }
            return true;
        }catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
    }

    @Override
    @Transactional
    public boolean checkSettlement(PuSettlement puSettlement){
        try{
            puSettlement.setShenhe(1);
            puSettlement.setShTime(new Date());
            puSettlementMapper.updateById(puSettlement);
            if(puSettlement.getDjlx()==2){
                WarehouseOrder warehouseOrder = warehouseOrderMapper.getByWoNo(puSettlement.getWoNo());
                warehouseOrder.setFpsl(new BigDecimal(BigDecimalUtil.add(warehouseOrder.getFpsl().doubleValue(),puSettlement.getQoQuantity().doubleValue())));
                warehouseOrder.setFpje(new BigDecimal(BigDecimalUtil.add(warehouseOrder.getFpje().doubleValue(),puSettlement.getWsje().doubleValue())));
                warehouseOrder.setZgsl(new BigDecimal(BigDecimalUtil.sub(warehouseOrder.getZgsl().doubleValue(),warehouseOrder.getFpsl().doubleValue())));
                Double cb = BigDecimalUtil.mul(warehouseOrder.getWsdj().doubleValue(),warehouseOrder.getZgsl().doubleValue());
                warehouseOrder.setZxcb(new BigDecimal(BigDecimalUtil.add(cb,warehouseOrder.getFpje().doubleValue())));
                warehouseOrderMapper.updateById(warehouseOrder);
            }
            return true;
        }catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
    }



    @Override
    @Transactional
    public boolean addHPuSettlement(PuSettlementVo puSettlementVo,String str){
       try{
           String precode = puBuyOrderMapper.getTeantCodeById(Integer.parseInt(str));
           PuBuyOrder puBuyOrder = puBuyOrderMapper.getByNumber(puSettlementVo.getPoOrder());
           WarehouseOrder warehouseOrder = warehouseOrderMapper.getByWoNo(puSettlementVo.getWoNo());
           PuSettlement yjSettlement = puSettlementMapper.getByPusNo(puSettlementVo.getPusNo());
           PuSettlement puSettlement = getPuSettlement(warehouseOrder,precode);
           puSettlement.setHsdj(yjSettlement.getHsdj());
           puSettlement.setWsdj(yjSettlement.getWsdj());
           puSettlement.setHxdh(yjSettlement.getPusNo());
           //TODO 预结算数量大于等于 入库单数量
           if(yjSettlement.getYhxTotail().doubleValue()>=warehouseOrder.getQoQuantity().doubleValue()){
               puSettlement.setQoQuantity(warehouseOrder.getQoQuantity());
               puSettlement.setRealityTotail(warehouseOrder.getQoQuantity());
               puSettlement.setPayTotail(warehouseOrder.getQoQuantity());
               puSettlement.setDtotail(warehouseOrder.getQoQuantity());
               puSettlement.setFpsl(warehouseOrder.getQoQuantity());
               warehouseOrder.setSupsttelemnt(new BigDecimal(BigDecimalUtil.sub(warehouseOrder.getSupsttelemnt().doubleValue(),puSettlement.getQoQuantity().doubleValue())));
               warehouseOrder.setIsSettlement(2);

           }else{ //TODO 预结算数量 小于入库单 数量
               puSettlement.setQoQuantity(yjSettlement.getYhxTotail());
               puSettlement.setRealityTotail(yjSettlement.getYhxTotail());
               puSettlement.setPayTotail(yjSettlement.getYhxTotail());
               puSettlement.setDtotail(yjSettlement.getYhxTotail());
               puSettlement.setFpsl(yjSettlement.getYhxTotail());
               warehouseOrder.setSupsttelemnt(new BigDecimal(BigDecimalUtil.sub(warehouseOrder.getSupsttelemnt().doubleValue(),yjSettlement.getYhxTotail().doubleValue())));
               warehouseOrder.setIsSettlement(1);
           }
           Double hsje = BigDecimalUtil.mul(puSettlement.getRealityTotail().doubleValue(),puSettlement.getHsdj().doubleValue());
           Double wsje =BigDecimalUtil.mul(puSettlement.getRealityTotail().doubleValue(),puSettlement.getWsdj().doubleValue());
           yjSettlement.setYhxTotail(new BigDecimal(BigDecimalUtil.sub(yjSettlement.getYhxTotail().doubleValue(),puSettlement.getQoQuantity().doubleValue())));
           yjSettlement.setYhxMoney(new BigDecimal(BigDecimalUtil.sub(yjSettlement.getYhxMoney().doubleValue(),hsje)));
           puBuyOrder.setYhxTotail(new BigDecimal(BigDecimalUtil.sub(puBuyOrder.getYhxTotail().doubleValue(),puSettlement.getQoQuantity().doubleValue())));
           puBuyOrder.setYhxMoney(new BigDecimal(BigDecimalUtil.sub(puBuyOrder.getYhxMoney().doubleValue(),hsje)));
           puSettlement.setHsje(new BigDecimal(hsje));
           puSettlement.setWsje(new BigDecimal(wsje));
           puSettlement.setPsTax(new BigDecimal(BigDecimalUtil.sub(hsje,wsje)));
           puSettlement.setHxdh(yjSettlement.getPusNo());
           puSettlement.setHtjjia(new BigDecimal(puBuyOrder.getHsdj()));
           puSettlement.setTradecode(warehouseOrder.getTradecode()!=null?warehouseOrder.getTradecode():null);
           puBuyOrderMapper.updateById(puBuyOrder);
           puSettlementMapper.insert(puSettlement);
           puSettlementMapper.updateById(yjSettlement);
           warehouseOrderMapper.updateById(warehouseOrder);
           return true;
       }catch (Exception e){
           e.printStackTrace();
           TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
           return false;
       }
    }

    public PuSettlement  getPuSettlement(WarehouseOrder warehouseOrder,String precode){
        PuSettlement puSettlement = new PuSettlement();
        String number = puSettlementMapper.getMaxCode();
        Map<String,String> codeMap = new HashMap<>();
        codeMap.put("maxCode",StringUtils.isBlank(number)?null:number);
        String name = precode+"JS_";
        String resultCode = generateOddUtil.createCode(codeMap,name);
        puSettlement.setPusNo(resultCode);
        puSettlement.setDjlx(2);
        puSettlement.setWhNum(warehouseOrder.getWhNum());
        puSettlement.setWoNo(warehouseOrder.getWoNo());
        puSettlement.setQoQuantity(warehouseOrder.getQoQuantity());
        puSettlement.setChumdwmc(warehouseOrder.getChumdwmc());
        Map<String,String > map = warehouseOrderMapper.getMapByCon(warehouseOrder.getPuConNo());
        puSettlement.setMaisdwmc(map.get("MAISDWMC"));
        puSettlement.setPoStaff(warehouseOrder.getPoStaff());
        puSettlement.setPusCdate(new Date());
        puSettlement.setCreateTime(new Date());
        puSettlement.setZhilzb(warehouseOrder.getZhilzb());
        puSettlement.setShanchu(0);
        puSettlement.setShenhe(1);
        puSettlement.setMeasureunit(warehouseOrder.getMeasureunit());
        puSettlement.setPuConNo(warehouseOrder.getPuConNo());
        puSettlement.setKouton(0.000);
        puSettlement.setShouyi(new BigDecimal(0.000));
        puSettlement.setAdjust(new BigDecimal(0.000));
        puSettlement.setRealzb(warehouseOrder.getRealzb());
        puSettlement.setDepartment(warehouseOrder.getDepartment());
        puSettlement.setProject(warehouseOrder.getProject());
        puSettlement.setFpsl(new BigDecimal(0.000));
        puSettlement.setCinvname(warehouseOrder.getCinvname());
        puSettlement.setPoOrder(warehouseOrder.getPoOrder());
        puSettlement.setZljf(new BigDecimal(0.000));
        puSettlement.setPayTotail(warehouseOrder.getQoQuantity());
        puSettlement.setRealityTotail(warehouseOrder.getQoQuantity());
        puSettlement.setKtotail(new BigDecimal(0.000));
        puSettlement.setDtotail(warehouseOrder.getQoQuantity());
        puSettlement.setPoTotail(warehouseOrder.getPoTotail());
        puSettlement.setZjzy(new BigDecimal(0.000));
        puSettlement.setTiexian(new BigDecimal(0.000));
        puSettlement.setIsInvoice(1);
        puSettlement.setCotoo("false");
        puSettlement.setSaleman(warehouseOrder.getSaleman());
        return  puSettlement;
    }



    @Override
    @Transactional
    public boolean addPuSettlement(PuSettlement puSettlement){
        try{
            WarehouseOrder warehouseOrder = warehouseOrderMapper.getByWoNo(puSettlement.getWoNo());

            Double yu=warehouseOrder.getSupsttelemnt().doubleValue();
            Double jie = puSettlement.getPayTotail().doubleValue();
            Double sup = BigDecimalUtil.sub(yu,jie);
            warehouseOrder.setSupsttelemnt(sup>=0?new BigDecimal(sup):new BigDecimal(0.000));
            warehouseOrder.setIsSettlement(warehouseOrder.getSupsttelemnt().doubleValue()>0?1:2);
            PuBuyOrder puBuyOrder = puBuyOrderMapper.getByNumber(warehouseOrder.getPoOrder());
            Map<String,String > map = new HashMap<>();
            if(puSettlement.getPuConNo()!=null) {
                map =  warehouseOrderMapper.getMapByCon(warehouseOrder.getPuConNo());
                if(map == null || map.isEmpty()){
                    map = warehouseOrderMapper.getMapBylrCon(warehouseOrder.getPuConNo());
                }

                if(map.get("MAISDWMC") != null){
                    puSettlement.setMaisdwmc(map.get("MAISDWMC"));
                }else{
                    puSettlement.setMaisdwmc("");
                }

            }
            puSettlement.setKtotail(puSettlement.getRealityTotail());
            puSettlement.setDtotail(puSettlement.getKtotail());
            puSettlement.setDjlx(warehouseOrder.getRklb()==4?3:puBuyOrder.getInvoice()==0?3:4);
            puSettlement.setYfhx(0);
            puSettlement.setIsInvoice(0);
            puSettlement.setTradecode(warehouseOrder.getTradecode()!=null?warehouseOrder.getTradecode():"");
            puSettlement.setShTime(null);
            warehouseOrderMapper.updateById(warehouseOrder);
            puSettlementMapper.insert(puSettlement);
            LoginUser user = sysBaseAPI.getUserById(puSettlement.getPoStaff());
            TemplateMessageDTO templateMessageDTO = new TemplateMessageDTO();
            templateMessageDTO.setFromUser("管理员");
            templateMessageDTO.setToUser(puSettlement.getSaleman()+",");
            templateMessageDTO.setTitle(TITLE);
            templateMessageDTO.setTemplateCode("order");
            Map<String, String> templateParam = new HashMap<>();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String date= simpleDateFormat.format(new Date());
            templateParam.put("ts_date",date);
            templateParam.put("ts_content", getMessage(user!=null?user.getRealname():"业务员不存在！", date));
            templateParam.put("checkOrder",puSettlement.getPusNo());
            templateParam.put("cd_url","/pubuySettlementOrder/puBuyOrderSettlement/list");
            templateMessageDTO.setTemplateParam(templateParam);
            sysBaseAPI.sendTemplateAnnouncement(templateMessageDTO);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
    }

    @Override
    @Transactional
    public boolean editPuSettlement(PuSettlement puSettlement){
        try{
            WarehouseOrder warehouseOrder = warehouseOrderMapper.getByWoNo(puSettlement.getWoNo());
            PuSettlement settlement = puSettlementMapper.getByPusNo(puSettlement.getPusNo());
            Double jie = BigDecimalUtil.add(warehouseOrder.getSupsttelemnt().doubleValue(),settlement.getPayTotail().doubleValue());
            warehouseOrder.setSupsttelemnt(new BigDecimal(BigDecimalUtil.sub(jie,puSettlement.getPayTotail().doubleValue())));
            if(warehouseOrder.getSupsttelemnt().doubleValue()>0){
                warehouseOrder.setIsSettlement(1);
            }else{
                warehouseOrder.setIsSettlement(2);
            }
            puSettlement.setKtotail(puSettlement.getRealityTotail());
            warehouseOrderMapper.updateById(warehouseOrder);
            puSettlementMapper.updateById(puSettlement);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
    }

    @Override
    @Transactional
    public boolean deletePuSettlement(PuSettlement puSettlement){
        try{
            if(puSettlement.getDjlx().toString().equals("1")){
                String[] poOrders = puSettlement.getPoOrder().split(",");
                if(poOrders.length > 1){
                    for (int i = 0;i < poOrders.length;i++){
                        PuBuyOrder puBuyOrder = puBuyOrderMapper.getByNumber(puSettlement.getPoOrder());
                        puBuyOrder.setYhxTotail(new BigDecimal(BigDecimalUtil.add(puSettlement.getRealityTotail().doubleValue(),puBuyOrder.getYhxTotail().doubleValue())));
                        puBuyOrder.setYhxMoney(new BigDecimal(BigDecimalUtil.add(puSettlement.getHsje().doubleValue(),puBuyOrder.getYhxMoney().doubleValue())));
                        puBuyOrderMapper.updateById(puBuyOrder);
                        puSettlementMapper.deleteById(puSettlement.getId());
                    }
                }else{
                    PuBuyOrder puBuyOrder = puBuyOrderMapper.getByNumber(puSettlement.getPoOrder());
                    puBuyOrder.setYhxTotail(new BigDecimal(BigDecimalUtil.add(puSettlement.getRealityTotail().doubleValue(),puBuyOrder.getYhxTotail().doubleValue())));
                    puBuyOrder.setYhxMoney(new BigDecimal(BigDecimalUtil.add(puSettlement.getHsje().doubleValue(),puBuyOrder.getYhxMoney().doubleValue())));
                    puBuyOrderMapper.updateById(puBuyOrder);
                    puSettlementMapper.deleteById(puSettlement.getId());
                }
                return true;
            }else{
                String[] wonos = puSettlement.getWoNo().split(",");
                if(wonos.length > 1){
                    for(int i = 0;i<wonos.length;i++){
                        WarehouseOrder warehouseOrder = warehouseOrderMapper.getByWoNo(wonos[i]);
                        PuBuyOrder puBuyOrder = puBuyOrderMapper.getByNumber(puSettlement.getPoOrder());
                        if(puSettlement.getHxdh()!=null && puSettlement.getDjlx()==2){
                            PuSettlement yjSettlement = puSettlementMapper.getByPusNo(puSettlement.getHxdh());
                            yjSettlement.setYhxMoney(new BigDecimal(BigDecimalUtil.add(puSettlement.getHsje().doubleValue(),yjSettlement.getYhxMoney().doubleValue())));
                            yjSettlement.setYhxTotail(new BigDecimal(BigDecimalUtil.add(puSettlement.getRealityTotail().doubleValue(),yjSettlement.getYhxTotail().doubleValue())));
                            puBuyOrder.setYhxTotail(new BigDecimal(BigDecimalUtil.add(puSettlement.getRealityTotail().doubleValue(),puBuyOrder.getYhxTotail().doubleValue())));
                            puBuyOrder.setYhxMoney(new BigDecimal(BigDecimalUtil.add(puSettlement.getHsje().doubleValue(),puBuyOrder.getYhxMoney().doubleValue())));
                            puSettlementMapper.updateById(yjSettlement);
                            puBuyOrderMapper.updateById(puBuyOrder);
                        }
                        Double ku = warehouseOrder.getSupsttelemnt().doubleValue();
                        Double jie = puSettlement.getPayTotail().doubleValue();
                        //warehouseOrder.setSupsttelemnt(new BigDecimal(BigDecimalUtil.add(ku,jie)));
                        //if(warehouseOrder.getSupsttelemnt().doubleValue()==warehouseOrder.getQoQuantity().doubleValue()){
                        warehouseOrder.setIsSettlement(0);
//                    }else{
//                        warehouseOrder.setIsSettlement(1);
//                    }
                        puSettlementMapper.deleteById(puSettlement.getId());
                        warehouseOrderMapper.updateById(warehouseOrder);
                        //return true;
                    }
                }else{
                    WarehouseOrder warehouseOrder = warehouseOrderMapper.getByWoNo(puSettlement.getWoNo());
                    PuBuyOrder puBuyOrder = puBuyOrderMapper.getByNumber(puSettlement.getPoOrder());
                    if(puSettlement.getHxdh()!=null && puSettlement.getDjlx()==2){
                        PuSettlement yjSettlement = puSettlementMapper.getByPusNo(puSettlement.getHxdh());
                        yjSettlement.setYhxMoney(new BigDecimal(BigDecimalUtil.add(puSettlement.getHsje().doubleValue(),yjSettlement.getYhxMoney().doubleValue())));
                        yjSettlement.setYhxTotail(new BigDecimal(BigDecimalUtil.add(puSettlement.getRealityTotail().doubleValue(),yjSettlement.getYhxTotail().doubleValue())));
                        puBuyOrder.setYhxTotail(new BigDecimal(BigDecimalUtil.add(puSettlement.getRealityTotail().doubleValue(),puBuyOrder.getYhxTotail().doubleValue())));
                        puBuyOrder.setYhxMoney(new BigDecimal(BigDecimalUtil.add(puSettlement.getHsje().doubleValue(),puBuyOrder.getYhxMoney().doubleValue())));
                        puSettlementMapper.updateById(yjSettlement);
                        puBuyOrderMapper.updateById(puBuyOrder);
                    }
                    Double ku = warehouseOrder.getSupsttelemnt().doubleValue();
                    Double jie = puSettlement.getPayTotail().doubleValue();
                    warehouseOrder.setSupsttelemnt(new BigDecimal(BigDecimalUtil.add(ku,jie)));
                    if(warehouseOrder.getSupsttelemnt().doubleValue()==warehouseOrder.getQoQuantity().doubleValue()){
                        warehouseOrder.setIsSettlement(0);
                    }else{
                        warehouseOrder.setIsSettlement(1);
                    }
                    puSettlementMapper.deleteById(puSettlement.getId());
                    warehouseOrderMapper.updateById(warehouseOrder);
                    return true;
                }
            }


        }catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
        return true;
    }
    @Override
    public List<PuSettlement> queryCaigouqushi() {
        return puSettlementMapper.queryCaigouqushi();
    }


}
